package web.server.io.handler.tst;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.server.io.handler.http.HttpServer;

public class TSTServer {

    private static final Logger log = LoggerFactory.getLogger(HttpServer.class);

    Integer port;

    Channel channel;

    public TSTServer(Integer port) {
        this.port = port;

    }
    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 10240) // 服务端可连接队列大小
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new TSTDecoder());
                        socketChannel.pipeline().addLast(new TSTHandler());
                    }
                });

        channel = bootstrap.bind(port).sync().channel();
        log.info("web server started on {}", port);
    }

    public static void main(String[] args) throws InterruptedException {
        TSTServer tstServer = new TSTServer(8877);
        tstServer.start();
    }

}
